﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using BookStore.Platform.objects;
using BookStore.WebAnalyzer;
using System.Xml;
using BookStore.Platform.utils;

namespace BookStore.Platform.apis
{
    public class RanWenBookListApi: BookListApi
    {
        private IBookApi bookApi = null;
        private IConvertApi convertApi = null;
        //WebClient webClient,
        public RanWenBookListApi(IWebAnalyzerApi webAnalyzerApi, IBookApi bookApi, IConvertApi convertApi)
            : base(webAnalyzerApi)
        {
          
            this.bookApi = bookApi;
            this.convertApi = convertApi;
        }

        private static string tableQuery = "//table[@class='sf-grid']";
        private static string catalogQuery = "//a[@class='STYLElvx']";
     
        private static string completedIndicator = "已完结";
        private static string maxPageNumerQuery = "//a[@class='last']";
        #region IBookListApi Members

        /// <summary>
        /// 下载全本小说
        /// </summary>
        /// <param name="url"></param>
        /// <param name="webSiteId"></param>
        /// <returns></returns>
        public override IList<objects.Book> GetCompletedBooksFromSingleWebPage(string url, Guid webSiteId)
        {
            XmlDocument doc = webAnalyzerApi.getXmlDocumentFromUrl(url);
            
            IList<XmlElement> trs = doc.GetNodesByTagAndAttributes("tr", "class", "odd");// tbody.SelectNodes("//tr");
            //DomNodeList trs = tbody.getElementsByTagName("tr");//get rows
            IList<Book> rets = new List<Book>();
            for (int i = 0; i < trs.Count; i++)
            {
                //get td
                IList<XmlElement> tds = trs[i].GetElementsByTagName("td").Cast<XmlElement>().ToList();
               

                //类别
                //string category = ((HtmlElement)tds.get(0)).getTextContent();
                string category = tds[0].InnerText;
                XmlNode bookNode = tds[1].GetElementsByTagName("a")[0];
                //名称
                string bookUrl = bookNode.Attributes["href"].Value;
                //bookUrl
                string bookName = WindowFolderNameCleaner.CleanName(bookNode.InnerText); //((HtmlAnchor)((HtmlElement)tds.get(1)).getElementsByTagName("a")).getHrefAttribute();
                //最后一章
                string lastChapter = tds[2].InnerText;// ((HtmlElement)tds.get(2)).getTextContent();
                //author
                string author = tds[3].InnerText; //((HtmlElement)tds.get(3)).getTextContent();
                //catalog
                XmlNode bookCatalogNode = tds[5].GetElementsByTagName("a")[0];
                string catalog = bookCatalogNode.Attributes["href"].Value;//((HtmlAnchor)((HtmlElement)tds.get(5)).getByXPath(catalogQuery)).getHrefAttribute();
                //status
                string status = tds[6].InnerText;// ((HtmlElement)tds.get(6)).getTextContent();
                //
                var entity = bookApi.GetByName(bookName, webSiteId);
                if (entity != null && entity.isDownloadCompleted) continue;            
                //如果书是新的， 或者 书的最后一章不是当前的最后一章
                if (entity == null || entity.LastChapter != lastChapter)
                {
                    //now only download 全本
                    if (status.Equals(completedIndicator))
                    {
                        Book tmp = new Book()
                        {
                            BookAuthor = author,
                            BookCatalogUrl = catalog,
                            BookCategory = category,
                            BookStatus = (status.Equals(completedIndicator)) ? BookStatus.completed : BookStatus.inProgress,
                            BookImage = "",
                            BookName = bookName,
                            BookSummary = "",
                            BookUrl = bookUrl,
                            Created = DateTime.Now,
                            Folder = bookName,
                            isDownloadCompleted = false,
                            LastChapter = lastChapter,
                            Updated = DateTime.Now,
                            WebSiteId = webSiteId
                        };
                        rets.Add(tmp);
                    }
                }
            }
            
            return rets;
        }

        public override int GetMaxPageNumber(string url) 
        {
            int maxPageNumber = 1;
            //HtmlPage firstPage = (HtmlPage)WebClient.getPage(url);
            //int.TryParse(((HtmlElement)firstPage.getByXPath(maxPageNumerQuery).get(0)).getTextContent(), out maxPageNumber);
            XmlDocument doc = webAnalyzerApi.getXmlDocumentFromUrl(url);
            IList<XmlElement> numberNodes = doc.GetNodesByTagAndAttributes("a", "class", "last");
            if (numberNodes.Count > 0)
            {
                int.TryParse(numberNodes[0].InnerText, out maxPageNumber);
            }
            return maxPageNumber;
        }
        #endregion
    }

   
}
